package blue.web.aop;

import blue.dao.base.BaseModel;
import blue.erp.model.BlueTeacher;
import blue.erp.model.SysUser;
import blue.tools.model.PageResponseData;
import blue.tools.model.ResponseData;
import blue.web.commons.UserContext;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class WebControllerAop {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * blue.web.controller..*.*(..)))")
    public void webController() {

    }

    @Before(value = "webController()")
    public void beforeWebController() {

    }

    @After(value = "webController()")
    public void afterWebController() {

    }

    @Around(value="webController()")
    public Object doAroundWebController(ProceedingJoinPoint pjp) throws Throwable {

        //对参数做操作
        Object[] args=pjp.getArgs();
        for(Object arg:args){

            if(arg instanceof BaseModel){
                ((BaseModel) arg).setSchoolid(UserContext.getSchoolId());
                Class argClas=arg.getClass();
                Method[] methodList=argClas.getMethods();
                if(methodList!=null && methodList.length>0){
                    for(Method method:methodList){
                        //增加默认操作者
                        if("setOperator".equalsIgnoreCase(method.getName())){
                           if( method.getParameterTypes()[0] == String.class){
                               method.invoke(arg,UserContext.getUserId().toString());
                           }else if(method.getParameterTypes()[0] == Long.class){
                               method.invoke(arg,UserContext.getUserId());
                           }
                        }

                        //增加默认更新时间
                        if("setUpdateTime".equalsIgnoreCase(method.getName())){
                            method.invoke(arg,new Date());
                        }

                        //如果有当前操作用户的话，将数据传入,像批量导入教师的这种要规避
                        if("setUserId".equalsIgnoreCase(method.getName()) && !(arg instanceof BlueTeacher)){
                            method.invoke(arg,UserContext.getUserId());
                        }
                    }
                }
            }

            if(arg instanceof String){
                arg=Convert.toDBC(((String) arg).trim());
            }

        }

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();

        logger.info(String.format("webController end,and userId=%s,result : %s ",
                UserContext.getUserId(),result==null?"":JSONObject.toJSONString(result)));

        //对用户账号做单独处理
        if(result instanceof ResponseData && ((ResponseData) result).getData() instanceof SysUser){
            SysUser sysUser= (SysUser) ((ResponseData) result).getData();
            sysUser.setSalt("fly-to-sky-and~");//干扰黑客
            sysUser.setPassword("");
            ((ResponseData) result).setData(sysUser);
        }

        if(result instanceof PageResponseData && CollectionUtils.isNotEmpty(((PageResponseData) result).getList())  && ((PageResponseData) result).getList().get(0) instanceof SysUser){
            for(Object sysUser:((PageResponseData) result).getList()){
                sysUser=(SysUser)sysUser;
                ((SysUser) sysUser).setSalt("fly-to-sky-and~");
                ((SysUser) sysUser).setPassword("");
            }
        }

        return result;
    }


}
